package com.wskj.supermarket.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 进行登陆验证的 过滤器
 * @author Administrator
 *
 */
@WebFilter(urlPatterns={"/*"},
initParams={@WebInitParam(name="allowed",value="js,css,img,jpg,png,bmp")})
public class LoginFilter implements Filter {
    //允许通过的 文件的格式  js,css,png图片等 ，具体需要可以在配置中配置
private	List<String> allowed=new ArrayList<String>();
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse resp=(HttpServletResponse)response;		
		//判断用户是否登陆
		
		//判断session 中是否有值 有值就直接放行
		Object user=req.getSession().getAttribute("user");
		
		if(user==null){
		 
			//获取请求的地址 
			String url = req.getRequestURI();			
			//排除  login.do  以及后缀名 css  png  js等文件 
			String  ext=url.substring(url.lastIndexOf(".")+1);			
			//最后的请求的路径 
			String action=url.substring(url.lastIndexOf("/")+1);
			
			//放行  
			if(allowed.contains(ext) || "login.do".equalsIgnoreCase(action)){
				chain.doFilter(req, resp);
			}else{				
				resp.sendRedirect(req.getContextPath()+"/login.do");
				return;			
			}
			
		}else{
		
		chain.doFilter(req, resp);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		String parameter = config.getInitParameter("allowed");
		String[] allows = parameter.split(",");
		allowed=Arrays.asList(allows);  
	}

}
